package com.mano.mall.service.auth.impl;

import com.alibaba.fastjson.JSONObject;
import com.mano.mall.api.auth.AuthorizationService;
import com.mano.mall.common.base.BaseApiService;
import com.mano.mall.common.base.BaseResponse;
import com.mano.mall.common.token.GenerateToken;
import com.mano.mall.service.mapper.AppInfoMapper;
import com.mano.mall.service.mapper.entity.AppInfo;
import com.mano.mall.service.utils.Guid;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AuthorizationServiceImpl extends BaseApiService<JSONObject> implements AuthorizationService {
	@Autowired
	private AppInfoMapper appInfoMapper;
	@Autowired
	private GenerateToken generateToken;

	@Override
	@Transactional
	@HystrixCommand(fallbackMethod = "defaultCallBackMethod")
	public BaseResponse<JSONObject> applyAppInfo(String appName) {
		if (StringUtils.isEmpty(appName)) {
			return setResultError("机构名称不能为空!");
		}
		// 1.生成appid
		Guid guid = new Guid();
		String appId = guid.getAppId();
		// 2.生成密钥
		String appScrect = guid.getAppScrect();
		// 3.插入到数据库中
		AppInfo appInfo = new AppInfo(appName, appId, appScrect);
		int insertAppInfo = appInfoMapper.insertAppInfo(appInfo);
		if (!toDaoResult(insertAppInfo)) {
			return setResultError("系统出现错误!");
		}
		JSONObject data = new JSONObject();
		data.put("appId", appId);
		data.put("appScrect", appScrect);
		return setResultSuccess(data);
	}

	@Override
	public BaseResponse<JSONObject> getAccessToken(String appId, String appSecret) {
		if (StringUtils.isEmpty(appId)) {
			return setResultError("appId不能为空!");
		}
		if (StringUtils.isEmpty(appSecret)) {
			return setResultError("appSecret不能为空!");
		}
		// 1.使用appId+appSecret查询数据库
		AppInfo appInfo = appInfoMapper.selectByAppInfo(appId, appSecret);
		if (appInfo == null) {
			return setResultError("appId或者是appSecret错误!");
		}
		// 2.生成accessToken
		String dbAppId = appInfo.getAppId();
		String accessToken = generateToken.createToken("auth", dbAppId);
		JSONObject data = new JSONObject();
		data.put("accessToken", accessToken);
		return setResultSuccess(data);
	}

	@Override
	public BaseResponse<JSONObject> getAppInfo(String accessToken) {
		if (StringUtils.isEmpty(accessToken)) {
			return setResultError("AccessToken cannot be empty ");
		}
		String appId = generateToken.getToken(accessToken);
		if (StringUtils.isEmpty(appId)) {
			return setResultError("accessToken  invalid");
		}
		AppInfo appInfo = appInfoMapper.findByAppInfo(appId);
		if (appInfo == null) {
			return setResultError("AccessToken  invalid");
		}
		JSONObject data = new JSONObject();
		data.put("appInfo", appInfo);
		return setResultSuccess(data);
	}

}
